import { _decorator, Component, EventTouch, find, input, Input, instantiate, Node, Prefab, v2, v3, Vec2 } from 'cc';
import { BowScript } from './BowScript';
import { LineScript } from './LineScript';
import DataManager from './Base/DataManager';
const { ccclass, property } = _decorator;

@ccclass('GameController')
export class GameController extends Component {
    //第一次点击位置
    private pos: Vec2
    private bow: BowScript
    private line: LineScript
    @property(Prefab)
    private ArrowPrefab: Prefab

    onLoad() {
        this.bow = this.node.getComponentInChildren(BowScript)
        this.line = this.node.getComponentInChildren(LineScript)
        input.on(Input.EventType.TOUCH_START, this.onMouseUp, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onMove, this);
        input.on(Input.EventType.TOUCH_END, this.onEnd, this);
    }

    onDestroy() {
        input.off(Input.EventType.TOUCH_START, this.onMouseUp, this);
        input.off(Input.EventType.TOUCH_MOVE, this.onMove, this);
        input.off(Input.EventType.TOUCH_END, this.onEnd, this);
    }

    onMouseUp(event: EventTouch) {
        // console.log(event.getLocation());  // Location on screen space
        // console.log(event.getUILocation());  // Location on UI space

        this.pos = event.getUILocation()
    }


    onMove(event: EventTouch) {
        this.line.cleat()
        this.line.drawLines(this.pos, event.getUILocation())

        //转动改变弓角度

        const radian = this.getAngle(event.getUILocation(), this.pos);

        this.bow.node.angle = radian

        console.log(radian)
    }

    onEnd(event: EventTouch) {
        // this.pos = null
        this.line.cleat()
        const leng = event.getUILocation().subtract(this.pos).length()
        //力直接用向量长度来计算...
        
        console.log("力",leng/10);
        this.fire(event, Math.abs(leng/10))
    }

    /**
     * 开火
     */
    protected fire(event: EventTouch, v :number){
        this.bow.fire(event, v)
    }

    update(deltaTime: number) {

    }

    /**
     * 获得两个方向向量的角度
     * @param dir1 
     * @param dir2 
     */
    getAngle(dir1: Vec2, dir2: Vec2){
        //计算出朝向
        // var dx = dir2.x - dir1.x;
        // var dy = dir2.y - dir1.y;
        // var dir = v2(dx,dy);

        const dir = dir1.subtract(dir2)
    
        //根据朝向计算出夹角弧度
        // var angle = dir.signAngle(v2(1,0));
        var angle = Math.atan2(dir.y, dir.x);
    
        //将弧度转换为欧拉角
        var degree = angle * (180 / Math.PI);
        // var degree = angle / Math.PI * 180;
        // const degree = angle * (180 / Math.PI);

        // return -(degree + 180)
        return degree + 180
    }

    huifang(){
        console.log("回放", DataManager.Instance.myState);

        const node = instantiate(this.ArrowPrefab)
        
        this.node.addChild(node)
        //把自己的位置角度都给它
        node.setWorldPosition(this.bow.node.getWorldPosition())
        node.setWorldRotation(this.bow.node.getWorldRotation())
    }
}


